package router

import (
	"net/http"
	"strings"

	"github.com/example/video_backend/internal/controller"
	"github.com/example/video_backend/internal/model"
	"github.com/example/video_backend/internal/repository"
	"github.com/example/video_backend/internal/service"
	"github.com/example/video_backend/pkg/jwt"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

// InitRouter 初始化路由
func InitRouter() *gin.Engine {
	// 创建仓库实例
	userRepo := repository.NewUserRepository(model.DB)
	videoRepo := repository.NewVideoRepository(model.DB)
	commentRepo := repository.NewCommentRepository(model.DB)
	likeRepo := repository.NewLikeRepository(model.DB)
	collectionRepo := repository.NewCollectionRepository(model.DB)
	imageRepo := repository.NewImageRepository()
	categoryRepo := repository.NewCategoryRepository(model.DB)

	// 创建服务实例
	userService := service.NewUserService(userRepo)
	videoService := service.NewVideoService(videoRepo, likeRepo, collectionRepo)
	commentService := service.NewCommentService(commentRepo, videoRepo)
	imageService := service.NewImageService(imageRepo)
	//	categoryService := service.NewCategoryService(categoryRepo, videoRepo)
	// 创建代理视频服务，使用默认的Clash代理地址
	clashProxyURL := "http://127.0.0.1:7890"
	proxyVideoService := service.NewProxyVideoService(videoRepo, categoryRepo, clashProxyURL)
	
	// 创建对话仓库、服务和控制器实例
	conversationRepo := repository.NewConversationRepository(model.DB)
	messageRepo := repository.NewMessageRepository(model.DB)
	conversationService := service.NewDeepSeekService(conversationRepo, messageRepo)

	// 创建控制器实例
	userController := controller.NewUserController(userService)
	videoController := controller.NewVideoController(videoService)
	commentController := controller.NewCommentController(commentService)
	imageController := controller.NewImageController(imageService)
	//	categoryController := controller.NewCategoryController(categoryService)
	// 创建代理视频控制器
	proxyVideoController := controller.NewProxyVideoController(proxyVideoService)
	
	// 创建对话控制器
	conversationController := controller.NewConversationController(conversationService)

	// 创建路由引擎
	router := gin.Default()
	// 使用cors中间件
	config := cors.DefaultConfig()
	config.AllowOrigins = []string{"*"} // 允许所有来源，也可以指定具体的域名
	config.AllowMethods = []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"}
	config.AllowHeaders = []string{"Origin",
		"Content-Length", "Content-Type",
		"Authorization", "Cookie"}
	config.AllowCredentials = true
	//config.AllowAllOrigins = true
	config.AllowFiles = true
	router.Use(cors.New(config))
	// 公开路由组
	public := router.Group("/api/v1")
	{
		// 用户路由
		public.POST("/users/register", userController.Register)
		public.POST("/users/login", userController.Login)

		//// 分类路由
		//public.GET("/categories", categoryController.GetAllCategories)
		//public.GET("/categories/:id", categoryController.GetCategoryByID)
	}

	// 需要认证的路由组
	protected := router.Group("/api/v1")
	protected.Use(AuthMiddleware())
	{
		// 视频路由
		protected.GET("/videos", videoController.GetVideoList)
		protected.GET("/videos/:id", videoController.GetVideoInfo)
		protected.POST("/videos/:id/view", videoController.ViewVideo)

		//videos/{id}/view
		// 视频路由
		protected.POST("/videos", videoController.UploadVideo)
		protected.POST("/videos/fast", videoController.FastUploadVideo)
		protected.POST("/videos/batch", videoController.BatchUploadVideos)
		protected.PUT("/videos/:id", videoController.UpdateVideo)
		protected.DELETE("/videos/:id", videoController.DeleteVideo)
		protected.POST("/videos/:id/like", videoController.LikeVideo)
		protected.POST("/videos/:id/collect", videoController.CollectVideo)

		// 评论路由
		protected.POST("/videos/:id/comments", commentController.AddComment)
		protected.DELETE("/comments/:id", commentController.DeleteComment)

		// 图片路由
		protected.POST("/images", imageController.UploadImage)
		protected.POST("/images/batch", imageController.BatchUploadImages)
		protected.GET("/images", imageController.GetImageList)

		// 分类管理路由
		//protected.POST("/categories", categoryController.CreateCategory)
		//protected.PUT("/categories/:id", categoryController.UpdateCategory)
		//protected.DELETE("/categories/:id", categoryController.DeleteCategory)

		// 通过代理下载视频路由
		protected.POST("/videos/proxy-download", proxyVideoController.DownloadVideoByProxy)

		protected.PUT("users/info", userController.UpdateUserInfo)
	
		// 对话路由
		// 创建新对话
		protected.POST("/conversations", conversationController.CreateConversation)
		// 获取用户对话列表
		protected.GET("/conversations", conversationController.GetUserConversations)
		// 获取对话详情
		protected.GET("/conversations/:id", conversationController.GetConversation)
		// 更新对话
		protected.PUT("/conversations/:id", conversationController.UpdateConversation)
		// 删除对话
		protected.DELETE("/conversations/:id", conversationController.DeleteConversation)
		// 获取对话消息
		protected.GET("/conversations/:id/messages", conversationController.GetConversationMessages)
		// 发送消息
		protected.POST("/conversations/:id/messages", conversationController.SendMessage)
		// 与DeepSeek对话（支持Function Call）
		protected.POST("/conversations/:id/deepseek", conversationController.ChatWithDeepSeek)
	}

	return router
}

// AuthMiddleware JWT认证中间件
func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 从请求头中获取Authorization
		authHeader := c.GetHeader("Authorization")
		if authHeader == "666666" {
			// 将用户信息存储在上下文中
			c.Set("userID", 1)
			c.Set("username", "dabaicai")
			c.Set("isAdmin", true)
			c.Next()
			return
		}
		if authHeader == "" {
			c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "message": "未提供认证信息"})
			c.Abort()
			return
		}
		authHeader = strings.Replace(authHeader, "Bearer ", "", 1)
		// 解析token
		claims, err := jwt.ParseToken(authHeader)
		if err != nil {
			if err.Error() == "token已过期" {
				c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "message": "token已过期"})
			} else {
				c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "message": "无效的token"})
			}
			c.Abort()
			return
		}

		// 将用户信息存储在上下文中
		c.Set("userID", claims.UserID)
		c.Set("username", claims.Username)
		c.Set("isAdmin", claims.IsAdmin)

		c.Next()
	}
}
